<template>
  <div id="ironLossFitting">
    <!-- 用于软磁性能的性能查询组件 -->
    <el-tooltip class="item" effect="dark" content="默认全选，支持手动选择测量数据" placement="top">
      <el-button type="primary" size="mini" style="width:120px" @click="showEdit()">铁损模型误差计算</el-button>
    </el-tooltip>
    <el-dialog title="铁损模型误差计算" :visible.sync="ironLossFittingVisible" width="70%" @close="reset(true)" class="main">
      <div class="left">
        <!-- <div class="latexId" v-html="'$$'+latex+'$$'"/> mathJax的显示 不用了-->
        <div class="item">
          <div class="title">模型说明</div>
          <div class="content">
            <el-link type="primary" @click="openPdf(1)" style="display: inline-block; margin-bottom: 5px">Examination of Temperature-Dependent Iron</el-link>
            <el-link type="primary" @click="openPdf(2)" style="display: inline-block;">Modeling of Temperature Effects on Magnetic Property</el-link>
          </div>
        </div>
        <div class="item">
          <div class="title">模型种类</div>
          <div class="content">
            <!-- <el-radio-group v-model="modelConflict" @change="modelConflictChange()"> -->
            <el-radio-group v-model="modelConflict" @change="formulaImgChange()">
              <el-radio v-for="item in modelConflictList" :label="item.value" :key="item.value" :disabled="modelConflict != item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="item">
          <div class="title">温度场</div>
          <div class="content">
            <!-- <el-radio-group v-model="temperatureField" @change="temperatureFieldChange()"> -->
            <el-radio-group v-model="temperatureField" @change="formulaImgChange()">
              <el-radio v-for="item in temperatureFieldList" :label="item.value" :key="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </div>
        </div>
        <div class="item">
          <div class="title">模型公式</div>
          <div class="content">
            <div class="imgShow">
              <img :src="modelFormulaImg" style="width: 100%; height: 100%;"/>
            </div>
          </div>
        </div>
        <div class="item tableItem">
          <div class="title">模型参数</div>
          <div class="content">
            <el-table :data="tableData" style="width: 100%" border @cell-mouse-enter="handleCellEnter" @cell-mouse-leave="handleCellLeave">
              <el-table-column prop="variableName" label="变量名" width="70px"></el-table-column>
              <el-table-column prop="parameterName" label="参数名" width="200px"></el-table-column>
              <el-table-column prop="value" label="值">
                <template slot-scope="scope">
                  <div class="item__txt">{{scope.row.value}}</div>
                  <el-input class="item__input" v-model="scope.row.value" placeholder="请输入值"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="item">
          <div class="title">模型误差</div>
          <div class="content">
            <div v-for="item in modelErrorList" :key="item.value">
              <div style="height: 34px; line-height: 34px; display: flex">
                <div class="modelErrorLabel" style="margin-right: 10px">{{ item.label }} = </div>
                <div class="modelErrorValue">{{ item.data }}</div>
              </div>
              <img :src="item.imgUrl" style="width: 100%; height: 80px;" />
            </div>
          </div>
        </div>
        <div class="leftBtn">
          <!-- <el-button type="primary" size="mini" style="width:100px" @click="imgConversion()">???</el-button> -->
          <el-button type="primary" size="mini" style="width:100px" @click="submit()">开始计算</el-button>
          <el-button type="primary" size="mini" style="width:100px" @click="reset(false)">重置</el-button>
        </div>
      </div>
      <div class="right" v-loading="submitLoading">
        <div class="item" style="margin-bottom: 4%; height: 550px;">
          <div class="title">铁损曲线</div>
          <div class="content">
            <div class="tools" v-if="ironLossCurveToolsFlag">
              <el-select v-model="temperatureList" placeholder="请选择温度" multiple clearable @change="ironLossCurveChange()">
                <el-option v-for="item in temperatureOptions" :key="item" :label="item + '℃'" :value="item"></el-option>
              </el-select>
              <el-select v-model="frequencyList" placeholder="请选择频率" multiple clearable @change="ironLossCurveChange()">
                <el-option v-for="item in frequencyOptions" :key="item" :label="item + 'Hz'" :value="item"></el-option>
              </el-select>
              <el-button type="primary" size="mini" style="32px !important" @click="ironDataDownLoad()">下载</el-button>
            </div>
            <div id="ironLossCurve" style="width: 100%; height: 100%;" v-loading="ironLossCurveLoading"></div>
          </div>
        </div>
        <div class="item" style="flex: 1">
          <div class="title">误差云图</div>
          <div class="tools" style="justify-content: flex-end; padding-right: 20px;">
            <el-button type="primary" size="mini" style="32px !important" @click="errorImgDownLoad()">下载</el-button>
          </div>
          <div class="content" id="errorCloudDiv">
            <el-carousel trigger="click" height="flex: 1 !important;" indicator-position="outside" class="carousel" :autoplay="false">
              <el-carousel-item v-for="item in errorCloudData.length" :key="item" class="carouselItem">
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="tipVisible" width="30%">
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import * as echarts from 'echarts'
import FNFormula from '../../../assets//formula/FNFormula.png'
import FTFormula from '../../../assets//formula/FTFormula.png'
import TNFormula from '../../../assets//formula/TNFormula.png'
import TTFormula from '../../../assets//formula/TTFormula.jpg'
import absoluteError from '../../../assets//formula/absoluteError.png'
import relativeError from '../../../assets//formula/relativeError.png'
// import MathJax from '../../../utils/MathJax';
import JSZip from "jszip";
import FileSaver from "file-saver";

export default {
  props: {},
  props: {
    selectNum: '',
    curve: '',
    parameterRowIdList: '',
  },
  data() {
    var checkData = (rule, value, callback) => {
      // 非负数 包括整数和小数
      var reg = /^[0-9]+([.]{1}[0-9]{1,100})?$/
      if (!value && rule.required == true) {
        callback(new Error('请输入非负数'))
      } else if (!value && rule.required == false) { //当没有值的时候，直接callback，让他不校验直接执行下一步
        return callback()
      }
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error('请输入非负数'))
        } else {
          if (value < 0) {
            callback(new Error('请输入非负数 '))
          } else {
            return callback()
          }
        }
      }, 100)
    }
    return {
      /******************** 组件显示 ************************/
      ironLossFittingVisible: false,
      tipVisible: false,
      /******************** 组件显示 ************************/
      /******************** left ************************/
      modelConflict: 0,
      temperatureField: 0,
      modelFormulaImg: TTFormula,
      modelError: 0,
      modelConflictList: [
        { value: 0, label: '时域Bertotti铁损模型', },
        { value: 1, label: '频域Bertotti铁损模型', },
      ],
      temperatureFieldList: [
        { value: 0, label: '考虑温度', },
        { value: 1, label: '不考虑温度', },
      ],
      modelErrorList: [
        { value: 0, label: '相对误差', imgUrl: absoluteError, data: '' },
        { value: 1, label: '绝对误差', imgUrl: relativeError, data: '' },
      ],
      // 需要编辑的属性
      editProp: ['value'],
      /******************** left ************************/
      /******************** tableData ************************/
      tableData: [ // tableData = TTData
        { variableName: 'Kh', parameterName: '% 磁滞损耗系数', value: '' },
        { variableName: 'x', parameterName: '% 磁滞损耗指数', value: '' },
        { variableName: 'Kec', parameterName: '% 经典涡流损耗系数', value: '' },
        { variableName: 'Ke', parameterName: '% 异常损耗系数', value: '' },
        { variableName: 'k', parameterName: '% 温度系数', value: '' },
        { variableName: 'T0', parameterName: '% 温度基值', value: '' },
      ],
      TTData: [
        { variableName: 'Kh', parameterName: '% 磁滞损耗系数', value: '' },
        { variableName: 'x', parameterName: '% 磁滞损耗指数', value: '' },
        { variableName: 'Kec', parameterName: '% 经典涡流损耗系数', value: '' },
        { variableName: 'Ke', parameterName: '% 异常损耗系数', value: '' },
        { variableName: 'k', parameterName: '% 温度系数', value: '' },
        { variableName: 'T0', parameterName: '% 温度基值', value: '' },
      ],
      TNData: [
        { variableName: 'Kh', parameterName: '% 磁滞损耗系数', value: '' },
        { variableName: 'x', parameterName: '% 磁滞损耗指数', value: '' },
        { variableName: 'Kec', parameterName: '% 经典涡流损耗系数', value: '' },
        { variableName: 'Ke', parameterName: '% 异常损耗系数', value: '' }
      ],
      FTData: [
        { variableName: 'a', parameterName: '% 磁滞损耗系数', value: '' },
        { variableName: 'x', parameterName: '% 磁滞损耗指数', value: '' },
        { variableName: 'b', parameterName: '% 经典涡流损耗系数', value: '' },
        { variableName: 'e', parameterName: '% 异常损耗系数', value: '' },
        { variableName: 'k', parameterName: '% 温度系数', value: '' },
        { variableName: 'T0', parameterName: '% 温度基值', value: '' },
      ],
      FNData: [
        { variableName: 'a', parameterName: '% 磁滞损耗系数', value: '' },
        { variableName: 'x', parameterName: '% 磁滞损耗指数', value: '' },
        { variableName: 'b', parameterName: '% 经典涡流损耗系数', value: '' },
        { variableName: 'e', parameterName: '% 异常损耗系数', value: '' },
      ],
      /******************** tableData ************************/
      /******************** mathJax ************************/
      // latex: 'y_i = x_i',
      /******************** mathJax ************************/
      /******************** ironLossCurve ************************/
      // ironLossCurveChart: [],
      submitLoading: false,
      ironLossCurveOptions: {
        xAxis: {
          name: 'bm/T',
          nameTextStyle: {
            color: 'skyblue',
            padding: [5, 0, 0, 0]
          },
          nameLocation: 'middle',
          axisLine: {
            onZero: false
          }
        },
        yAxis: {
          name: 'Ps/(W/kg)',
          position: 'left',
          nameTextStyle: {
            color: 'green'
          },
          axisLine: {
            show: true,
            onZero: false
          }
        },
        tooltip: {
          confine: true,
          formatter: function() {
          	// console.log(arguments)
          	// console.log(arguments[0])
          	// console.log(arguments[0].data)
            return 'x : ' + arguments[0].data[0] + '<br/>' + 'y : ' + arguments[0].data[1]
          }
        },
        series: [
          {
            type: 'line'
          }
        ],
        grid: [{ top: 50, }],
        legend: {
          data: [],
          icon: 'none',
          textStyle: {
            color: 'inherit'
          },
          orient: "vertical",
        }
      },
      ironLossCurveToolsFlag: false,
      allSeriesData: [],
      temperatureOptions: [],
      temperatureList: [],
      frequencyOptions: [],
      frequencyList: [],
      ironLossCurveLoading: false,
      /******************** ironLossCurve ************************/
      /******************** errorCloud ************************/
      errorCloudOptions: {
        xAxis: {
          name: '',
          nameTextStyle: {
            color: 'skyblue',
            padding: [5, 0, 0, 0]
          },
          nameLocation: 'middle',
          axisLine: {
            onZero: false
          }
        },
        yAxis: {
          name: '',
          position: 'left',
          nameTextStyle: {
            color: 'green'
          },
          axisLine: {
            onZero: false
          }
        },
        tooltip: {
          confine: true,
          formatter: function() {
          	// console.log(arguments)
          	// console.log(arguments[0])
          	// console.log(arguments[0].data)
            return 'x : ' + arguments[0].data[0] + '<br/>' + 'y : ' + arguments[0].data[1]
          }
        },
        series: []
      },
      errorCloudLoading: false,
      errorCloudData: [],
      /******************** errorCloud ************************/
      sourceData: [],
    }
  },
  mounted() {
    // this.drawChart();
  },
  watch: {
    // latex() {
    //   this.formatMath()
    // },
  },
  created(){
  	// this.formatMath();
    // this.sourceDataTransfer()
    // this.imgConversion()
    // this.errorCloudDataTransfer()
    this.drawChart()
    // this.showEdit()
  },
  methods: {
    showEdit() {
      this.ironLossFittingVisible = true
      Message({
        message: '请填写模型参数信息！',
        type: 'warning',
        center: true,
        customClass: 'myMessageClass'
      })
      if (this.curve == '磁滞回线') {
        this.modelConflict = 0
      } else if (this.curve == '铁损曲线') {
        this.modelConflict = 1
      }
      this.$nextTick(()=>{this.formulaImgChange()})
    },
    drawChart() {
      var ironLossCurveDom = document.getElementById('ironLossCurve');
      // var errorCloudDom = document.getElementById('errorCloud');
      if(!ironLossCurveDom) {
        setTimeout(() => {
          this.drawChart();
        },500);
      } else {
        this.ironLossCurveChart = echarts.init(ironLossCurveDom)
        this.ironLossCurveChart.setOption(this.ironLossCurveOptions,true)
        this.$nextTick(()=>{this.ironLossCurveChart.resize()})
      }
      // if(!errorCloudDom) {
      //   setTimeout(() => {
      //     this.drawChart();
      //   },500);
      // } else {
      //   this.errorCloudChart = echarts.init(errorCloudDom)
      //   this.errorCloudChart.setOption(this.errorCloudOptions,true)
      //   this.$nextTick(()=>{this.errorCloudChart.resize()})
      // }
    },
    // 渲染MathJax
    // formatMath(){
	  //   setTimeout(() => {
    //       this.$nextTick(function () { //这里要注意，使用$nextTick等组件数据渲染完之后再调用MathJax渲染方法，要不然会获取不到数据
    //         if(this.MathJax.isMathjaxConfig){//判断是否初始配置，若无则配置。
    //             this.MathJax.initMathjaxConfig();
    //         }
    //         this.MathJax.MathQueue("latexId");//传入组件id，让组件被MathJax渲染
    //       })
    //   },5000)
	  // },
    /** 重置: 表格value值, 各选项  */
    submit() {
      // this.sourceDataTransfer()
      console.log('this.modelConflict', this.modelConflict)
      console.log('this.temperatureField', this.temperatureField)
      console.log('this.tableData', this.tableData)
      console.log('this.selectNum', this.selectNum)
      for (let index = 0; index < this.tableData.length; index++) {
        if(this.tableData[index].value == '' || this.tableData[index].value.length == 0 || this.tableData[index].value == null) {
          Message({
            message: '参数值未全部填写！',
            type: 'warning',
            center: true,
            customClass: 'myMessageClass'
          })
          return
        }
      }
      if(this.selectNum == undefined || this.selectNum == null || this.selectNum == '' || this.selectNum.length == 0) {
        Message({
          message: '未勾选样品，无编号值！',
          type: 'warning',
          center: true,
          customClass: 'myMessageClass'
        })
        return
      }
      var paramList = this.tableData.map((item) => {
        return { label: item.variableName, value: item.value }
      })
      console.log('paramList', paramList)
      this.submitLoading = true
      this.axios({
        baseURL: 'http://59.172.104.174:30669',
        url: `/matlab/bertottifreq`,
        method: 'POST',
        data: {
          "num": this.selectNum,
          // "productDynamicIronLossNum": 562,
          "ModelType": this.modelConflict,
          "TemperatureField": this.temperatureField,
          "paramList": paramList,
          "parameterRowIdList": this.parameterRowIdList,
        },
      }).then(res => {
        console.log(res);
        if(res.data.result.matlabError == true) {
          Message({
            message: res.data.result.ErrorMessage,
            type: 'error',
            center: true,
            customClass: 'myMessageClass'
          })
          this.submitLoading = false
          return
        } else {
          var data = res.data.result
          this.sourceData = data.data
          this.errorCloudData = data.jpgList
          this.modelErrorList[0].data = data.相对误差
          this.modelErrorList[1].data = data.绝对误差
          this.imgConversion()
          this.sourceDataTransfer()
          this.submitLoading = false
        }
      })
    },
    reset(flag) {
      this.ironLossFittingVisible = !flag // 重置不关闭窗口 取消则关闭
      this.modelConflict = 0
      this.temperatureField = 0
      this.modelFormulaImg = TTFormula
      this.modelError = 0
      this.tableData = JSON.parse(JSON.stringify(this.TTData))
      for (let index = 0; index < this.tableData.length; index++) {
        this.tableData[index].value = ''
      }
      this.ironLossCurveOptions.series = []
      this.ironLossCurveOptions.legend.data = []
      this.errorCloudOptions.series = []
      this.errorCloudData = []
      this.ironLossCurveOptions.series = []
      this.allSeriesData = []
      this.temperatureOptions = []
      this.frequencyOptions = []
      this.temperatureList = []
      this.frequencyList = []
      this.drawChart()
    },
    modelConflictChange() {
      // console.log('modelConflict-----------', this.modelConflict)
      this.formulaImgChange()
    },
    temperatureFieldChange() {
      // console.log('temperatureField-----------', this.temperatureField)
      this.formulaImgChange()
    },
    /** 表格和公式图片切换 */
    formulaImgChange() {
      // console.log('modelConflict,temperatureField-----------', this.modelConflict, this.temperatureField)
      if(this.modelConflict == 0 && this.temperatureField == 0) {
        this.modelFormulaImg = TTFormula
        this.tableData = JSON.parse(JSON.stringify(this.TTData))
      } else if(this.modelConflict == 0 && this.temperatureField == 1) {
        this.modelFormulaImg = TNFormula
        this.tableData = JSON.parse(JSON.stringify(this.TNData))
      } else if(this.modelConflict == 1 && this.temperatureField == 0) {
        this.modelFormulaImg = FTFormula
        this.tableData = JSON.parse(JSON.stringify(this.FTData))
      } else if(this.modelConflict == 1 && this.temperatureField == 1) {
        this.modelFormulaImg = FNFormula
        this.tableData = JSON.parse(JSON.stringify(this.FNData))
      }
    },
    /** 鼠标移入cell */
    handleCellEnter (row, column, cell, event) {
      // console.log('row', row)
      // console.log('column', column)
      // console.log('cell', cell)
      const property = column.property
      if (this.editProp.includes(property)) {
        cell.querySelector('.item__input').style.display = 'block'
        cell.querySelector('.item__txt').style.display = 'none'
      }
    },
    /** 鼠标移出cell */
    handleCellLeave (row, column, cell, event) {
      // console.log('row', row)
      // console.log('column', column)
      // console.log('cell', cell)
      const property = column.property
      if (this.editProp.includes(property)) {
        cell.querySelector('.item__input').style.display = 'none'
        cell.querySelector('.item__txt').style.display = 'block'
      }
    },
    openPdf(flag) {
      if(flag == 1) {
        window.open('http://59.172.104.174:32152/static/MOTDI.pdf')
      } else if (flag == 2) {
        window.open('http://59.172.104.174:32152/static/MOTEOMP.pdf')
      }
    },
    sourceDataTransfer() {
      this.ironLossCurveOptions.series = []
      this.allSeriesData = []
      this.temperatureOptions = []
      this.frequencyOptions = []
      // 查找数据中温度和频率种类
      this.temperatureOptions = [...new Set(Array.from(this.sourceData,({temperature})=>temperature))]
      this.frequencyOptions = [...new Set(Array.from(this.sourceData,({frequency})=>frequency))]
      this.temperatureList = []
      this.frequencyList = []
      this.temperatureList.push(this.temperatureOptions[0])
      this.frequencyList.push(this.frequencyOptions[0])
      // 数据根据频率和温度分组放入series中
      this.sourceData.map(mapItem => {
        if (this.allSeriesData.length == 0) {
          this.allSeriesData.push({ type : 'line', data: [[mapItem.fluxDensity,mapItem.fittedIronLoss]], name : mapItem.temperature + '℃ ' + mapItem.frequency + 'Hz 拟合铁损' })
          this.allSeriesData.push({ type : 'line', data: [[mapItem.fluxDensity,mapItem.measureIronLoss]], name : mapItem.temperature + '℃ ' + mapItem.frequency + 'Hz 实测铁损' })
        } else {
          let res = this.allSeriesData.some((item,index)=> {  //判断是否有相同属性
            if (item.name.substring(0,item.name.length-5) == (mapItem.temperature + '℃ ' + mapItem.frequency + 'Hz')) {
              item.data.push([mapItem.fluxDensity,mapItem.fittedIronLoss])
              this.allSeriesData[index + 1].data.push([mapItem.fluxDensity,mapItem.measureIronLoss])
              return true
            }
            return false
          })
          if (!res) {  //若无相同属性
            this.allSeriesData.push({ type : 'line', data: [[mapItem.fluxDensity,mapItem.fittedIronLoss]], name : mapItem.temperature + '℃ ' + mapItem.frequency + 'Hz 拟合铁损' })
            this.allSeriesData.push({ type : 'line', data: [[mapItem.fluxDensity,mapItem.measureIronLoss]], name : mapItem.temperature + '℃ ' + mapItem.frequency + 'Hz 实测铁损' })
          }
        }
      })
      console.log('this.allSeriesData---------', this.allSeriesData)
      // console.log('this.ironLossCurveOptions---------', this.ironLossCurveOptions)
      console.log('this.temperatureOptions---------', this.temperatureOptions)
      console.log('this.frequencyOptions---------', this.frequencyOptions)
      this.ironLossCurveChange();
      this.ironLossCurveToolsFlag = true
      // console.log('this.ironLossCurveOptions---------', this.ironLossCurveOptions)
      // this.ironLossCurveChart.setOption(this.ironLossCurveOptions,true)
    },
    ironLossCurveChange() {
      this.ironLossCurveOptions.series = []
      this.ironLossCurveOptions.legend.data = []
      this.ironLossCurveLoading = true
      if (this.temperatureList.length == 0 && this.frequencyList == 0) {
        Message({
          message: '请选择温度和频率',
          center: true,
          type: 'warning',
          customClass: 'myMessageClass'
        })
        return
      } else if (this.temperatureList.length == 0 && this.frequencyList != 0) {
        Message({
          message: '请选择温度',
          center: true,
          type: 'warning',
          customClass: 'myMessageClass'
        })
        return
      } else if (this.temperatureList.length != 0 && this.frequencyList == 0) {
        Message({
          message: '请选择频率',
          center: true,
          type: 'warning',
          customClass: 'myMessageClass'
        })
        return
      }
      console.log('this.temperatureList', this.temperatureList)
      console.log('this.frequencyList', this.frequencyList)
      var combinedArray = []
      for (let i = 0; i < this.temperatureList.length; i++) {
        for (let j = 0; j < this.frequencyList.length; j++) {
          combinedArray.push(this.temperatureList[i] + '℃ ' + this.frequencyList[j]  + 'Hz 实测铁损')
          combinedArray.push(this.temperatureList[i] + '℃ ' + this.frequencyList[j]  + 'Hz 拟合铁损')
        }
      }
      console.log('--------------------------------------------------------------------------------------------------')
      // console.log('this.allSeriesData---------', this.allSeriesData)
      // console.log('combinedArray---------', combinedArray)
      for (let i = 0; i < this.allSeriesData.length; i++) {
        for (let j = 0; j < combinedArray.length; j++) {
          if (this.allSeriesData[i].name == combinedArray[j]) {
            this.ironLossCurveOptions.series.push(this.allSeriesData[i])
            this.ironLossCurveOptions.legend.data.push(this.allSeriesData[i].name)
            break
          }
        }
      }
      console.log('this.ironLossCurveOptions.series---------', this.ironLossCurveOptions.series)
      this.ironLossCurveOptions.grid[0].top = 25 * this.ironLossCurveOptions.legend.data.length
      // this.graphHeight = 500 + 30 * res.data.result.list.length
      this.drawChart();
      // this.ironLossCurveChart.setOption(this.ironLossCurveOptions,true)
      this.ironLossCurveLoading = false
    },
    drawChartHeight(relHeight) {
      this.ironLossCurveChart.clear()
      this.ironLossCurveChart.hideLoading()
      this.ironLossCurveChart.setOption(this.ironLossCurveOptions,true)
      const autoHeight = relHeight
      this.ironLossCurveChart.resize()
      this.ironLossCurveLoading = false
    },
    errorCloudDataTransfer() {
      this.errorCloudOptions.series = []
      var errorCloudList = []
      var errorCloudTempList = [...new Set(Array.from(this.errorCloudSourceData,({temp})=>temp))]
      console.log('errorCloudList---------', errorCloudList)
      for (let i = 0; i < errorCloudTempList.length; i++) {
        errorCloudList[i] = {
          temp: this.errorCloudSourceData[ 3 * i].temp,
          f_mesh: this.errorCloudSourceData[ 3 * i].f_mesh,
          Bm_mesh: this.errorCloudSourceData[ 3 * i + 1 ].Bm_mesh,
          RelErr_mesh: this.errorCloudSourceData[ 3 * i + 2 ].RelErr_mesh,
        }
      }
      console.log('errorCloudList---------', errorCloudList)
      
      for (let index = 0; index < errorCloudList.length; index++) {
        var uniqueArr = [...new Set(Array.from(errorCloudList[index].RelErr_mesh))]
        var keyArr = []
        // 多少条等值线 = uniqueArr.length = keyArr.length
        for (let i = 0; i < uniqueArr.length; i++) {
          // value为等值线取值；valueList为原数组内下标
          keyArr.push({ value: uniqueArr[i], valueList: this.searchKeys(uniqueArr[i],errorCloudList[index].RelErr_mesh) })
        }
        console.log('uniqueArr---------', uniqueArr)
        console.log('keyArr---------', keyArr)
        // 每条等值线中有多少数据
        console.log('keyArr.length---------', keyArr.length)
        for (let j = 0; j < keyArr.length; j++) {
          this.errorCloudOptions.series.push({
            type : 'line', 
            data: [], 
            name : errorCloudList[index].temp + " : " +  keyArr[j].value
          })
          for (let k = 0; k < keyArr[j].valueList.length; k++) {
            this.errorCloudOptions.series[j].data.push([ errorCloudList[index].f_mesh[keyArr[j].valueList[k]], errorCloudList[index].Bm_mesh[keyArr[j].valueList[k]] ])
          }
        }
      }
      console.log('this.errorCloudOptions.series---------', this.errorCloudOptions.series)
    },
    // 获取相同值的数组下标
    searchKeys(needle, haystack){
      var result = [];
      for (var i in haystack) {
        if (haystack[i] == needle) {
            result.push(i);
        }
      }
      return result
    },
    // base64图片格式转为url格式
    getBase64URL(pic) {
        const blob = this.base64ImgToFile(pic)
        const blobUrl = window.URL.createObjectURL(blob);
        return blobUrl
    },
    base64ImgToFile(dataurl, filename = 'file') {
        //将base64格式分割：['data:image/png;base64','XXXX']
        const arr = dataurl[0].split(',')
        // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
        // image/png
        const mime = arr[0].match(/:(.*?);/)[1]  //image/png
        //[image,png] 获取图片类型后缀
        const suffix = mime.split('/')[1] //png
        const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, {
            type: mime
        })
    },
    // img放入显示
    imgConversion() {
      var carousel = document.getElementsByClassName("carousel");
      var carouselItem = document.getElementsByClassName("carouselItem");
      // console.log('carouselItem', carouselItem)
      console.log('this.errorCloudData.length', this.errorCloudData.length)
      this.$nextTick(() => {
        for (let i = 0; i < this.errorCloudData.length; i++) {
          var img = new Image();
          // console.log('carouselItem[i]', carouselItem[i])
          img.src = Object.values(this.errorCloudData[i])
          img.style.width = '100%'
          img.style.height = '100%'
          // carousel.appendChild('<el-carousel-item v-for="item in errorCloudData.length" :key="item" class="carouselItem"><div></div></el-carousel-item>');
          // var carouselItem = document.getElementsByClassName("carouselItem");
          carouselItem[i].appendChild(img);
        }
      })
    },
    ironDataDownLoad() {
      console.log('this.allSeriesData---------', this.allSeriesData)
      var fileData = ''
      for (let i = 0; i < this.allSeriesData.length; i++) {
        // fileData += '曲线：' + this.allSeriesData[i].name + '\n'
        fileData += this.allSeriesData[i].name + '\n'
        fileData += 'x' + '  ' + 'y' + '\n'
        for (let j = 0; j < this.allSeriesData[i].data.length; j++) {
          fileData += this.allSeriesData[i].data[j][0] + '  ' + this.allSeriesData[i].data[j][1] + '\n'
        }
        fileData += '\n'
      }
      var fileName = 'fileName'
      // console.log(fileData,"fileData");
      if(this.allSeriesData.length == 0 || this.allSeriesData == []) {
        Message({
          message: '曲线数据为空，无法下载！',
          center: true,
          type: 'error',
          customClass:'myMessageClass'
        })
        return
      } else {
        fileName = '铁损曲线数据.txt'
        // var fileData = this.options.series[0].data
        var urlObject = window.URL || window.webkitURL || window;
        var export_blob = new Blob([fileData]);
        var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
        save_link.href = urlObject.createObjectURL(export_blob);
        save_link.download = fileName;
        this.fakeClick(save_link);
      }
    },
    fakeClick(obj) {
      var ev = document.createEvent("MouseEvents");
      ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      obj.dispatchEvent(ev);
    },
    errorImgDownLoad() {
      console.log('this.errorCloudData', this.errorCloudData)
      if (this.errorCloudData == [] || this.errorCloudData.length == 0 || this.errorCloudData == undefined || this.errorCloudData == null) {
        Message({
          message: '无误差云图可下载！',
          center: true,
          type: 'error',
          customClass:'myMessageClass'
        })
        return
      } else {
        var fileArr = this.errorCloudData.map(item => {return {fileDownName: Object.keys(item), fileDownUrl: this.getBase64URL(Object.values(item)), aHref: Object.values(item)[0] } })
        console.log('fileArr', fileArr)
        this.downImgZip(fileArr)
      }
    },
    getFile(url) {
      return new Promise((resolve, reject) => {
        this.axios({
          method: "get",
          url, // 原先后端下载单个文件的路径
          // responseType: "ArrayBuffer"  // 注意看下你自己的原先后端下载地址返回的文件格式 是blob 还是其他的啥 对应这里就要改成后端返回的下载格式
          responseType: "blob"
        })
          .then(res => {
            resolve(res.data) // 返回文件的blob   Blob {size: 151382, type: 'image/png'}
          })
          .catch(error => {
            reject(error.toString())
          })
      })
    },
    downFileZip(arr) {
      // 这个是下载的文件的数组  一般会先调用一个后端接口，得到所有需要下载的文件的路径和对应名称（包含后缀名）
      // const arr = [{fileDownUrl:'地址', fileDownName:'文件名'}] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
      const zip = new JSZip()
      const cache = {}
      const promises = []
      arr.forEach((item, i) => {
        const promise = this.getFile(item.fileDownUrl).then(data => {
          // 下载文件, 并存成blob对象
          const file_name = i + 1 + item.fileDownName // 获取文件名，一定要包含文件的后缀名(因为重复的文件名只会下载一个，故需要加入下标 不同名)
          zip.file(file_name, data, { binary: true }) // 逐个添加文件
          cache[file_name] = data
        })
        promises.push(promise)
      })
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: "blob" }).then(content => {
          // 生成二进制流   然后保存文件（如果这个下载不了 也可以将下方这一行换成a标签下载逻辑）
          FileSaver.saveAs(content, "铁损模型误差分布图.zip") // 利用file-saver保存文件  自定义文件名
        })
      })
    },
    downImgZip(sourceList, zipName = '铁损模型误差分布图') {
      const zip = new JSZip()
      // const fileFolder = zip.folder(zipName) // 创建 zipName 文件夹
      const fileList = []
      for (let i = 0; i < sourceList.length; i++) {
        const name = sourceList[i].fileDownName // 注意: 每张图片的名称--需要对数据属性进行转换
        const image = new Image()
        image.setAttribute('crossOrigin', 'Anonymous') // 设置 crossOrigin 属性，解决图片跨域报错
        image.src = sourceList[i].fileDownUrl
        image.onload = async() => {
          const url = sourceList[i].aHref
          fileList.push({ name: name, img: url.substring(22) }) // 截取 data:image/png;base64, 后的数据
          if (fileList.length === sourceList.length) {
            if (fileList.length) {
              for (let k = 0; k < fileList.length; k++) {
                // fileFolder.file(fileList[k].name, fileList[k].img, {
                //   base64: true
                // })
                zip.file('铁损模型误差分布图@' + fileList[k].name + '.png', fileList[k].img, { base64: true })
              }
              zip.generateAsync({ type: 'blob' }).then(content => {
                FileSaver.saveAs(content, zipName + '.zip')
              })
            }
          }
        }
      }
    },
  }
}
</script>

<style lang="less" scoped>
.myMessageClass {
  z-index:5000 !important;
}
#ironLossFitting{
  .main {
    /deep/.el-dialog__body {
      display: flex;
      padding: 2% !important;
    }
    .left {
      width: 35%;
      margin-right: 5%;
      display: flex;
      flex-flow: column;
      justify-content: space-between;
      .item {
        border: 1px solid #DCDFE6;
        margin-bottom: 5%;
        .title {
          height: 48px;
          line-height: 48px;
          border-bottom: 1px solid #DCDFE6;
          padding-left: 20px;
        }
        .content {
          padding: 10px 10px 10px 20px;
          /deep/.el-radio {
            display: block;
            height: 24px;
            line-height: 24px;
          }
          .modelErrorRadio {
            display: flex;
            height: 100%;
            margin-bottom: 20px;
            /deep/.el-radio__inner {
              margin-top: 5px;
            }
          }
        }
        .item__input{
          display: none;
          width: 100px;
        }
        .item__txt{
          box-sizing: border-box;
          line-height: 24px;
          padding: 0 9px;
        }
      }
      .tableItem {
        border: none;
        .title {
          border: 1px solid #DCDFE6;
          border-bottom: none;
        }
        .content {
          padding: 0;
          div {
            border-color: #DCDFE6;
          }
          /deep/.el-table__cell {
            padding: 0!important;
            height: 24px;
            line-height: 24px;
          }
          /deep/.cell {
            display: flex !important;
            justify-content: center;
            align-items: center;
            font-weight: 500;
            color: #606266;;
          }
        }
      }
      .leftBtn {
        display: flex;
        justify-content: flex-end;
      }
    }
    .right {
      width: 60%;
      display: flex;
      flex-direction: column;
      .item {
        // height: 48%;
        // min-height: 550px;
        border: 1px solid #DCDFE6;
        display: flex;
        flex-direction: column;
        .title {
          height: 30px;
          line-height: 24px;
          text-align: center;
          border-bottom: 1px solid #DCDFE6;
        }
        .tools {
          display: flex;
          justify-content: space-around;
          padding: 10px 0;
          align-items: center;
        }
        .content {
          flex: 1;
          display: flex;
          flex-direction: column;
          #ironLossCurve, #errorCloud {
            flex: 1;
            padding: 10px 10px 0 10px;
          }
        }
      }
      .carousel.el-carousel.el-carousel--horizontal {
        height: 100%;
        display: flex;
        flex-direction: column;
        /deep/.el-carousel__container {
          flex: 1 !important;
        }
      }
    }
  }
}
</style>
